package com.westos.userauth.service.impl;

import com.westos.userauth.dao.*;
import com.westos.userauth.domain.*;
import com.westos.userauth.dto.SecurityPermissionDto;
import com.westos.userauth.service.Security;
import com.westos.userauth.service.impl.PartyServiceImpl;
import com.westos.userauth.util.MD5Util;
import org.apache.commons.codec.binary.StringUtils;

import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SecurityImpl implements Security {
    @Autowired
    private SecurityGroupDao securityGroupDao;
    @Autowired
    private UserLoginDao userLoginDao;
    @Autowired
    private SecurityGroupPermissionDao securityGroupPermissionDao;
    @Autowired
    private UserLoginSecurityGroupDao userLoginSecurityGroupDao;
    @Autowired
    private SecurityPermissionDao securityPermissionDao;
    @Autowired
    private UserLoginSecurityQuestionDao userLoginSecurityQuestionDao;
    private Logger logger = LoggerFactory.getLogger(PartyServiceImpl.class);

    @Override// 根据用户名查找用户的权限组（有效时间内）（方政）
    public List<UserLoginSecurityGroup> findUserLoginSecurityGroupByUserLoginId(String userLoginId) {
        return userLoginSecurityGroupDao.queryGroupIdByLoginId(userLoginId);
    }

    @Override//权限是否在权限组中（方政）
    public boolean securityGroupPermissionExists(String permissionId, String groupId) {
        return securityGroupPermissionDao.querySecurityGroupPermissionById(permissionId, groupId).size()>=1;
    }

    @Override//用户是否有权限（方政）(后期内容优化：缓存机制)
    public boolean hasPermission(String permissionId, String loginId) {
        return securityGroupPermissionDao.querySecurityGroupPermissionByLoginId(permissionId, loginId).size()>=1;
    }

    @Override //是否有角色权限（方政）(空着)
    public boolean hasRolePermission(String permissionId, String groupId) {
        return false;
    }

    @Override//===添加权限到权限组（刘浩）
    public boolean addSecurityPermissionToSecurityGroup(SecurityPermissionDto securityPermissionDto) {
        if (securityPermissionDto.getPermissionId() == null || securityPermissionDto.getPermissionId().equals("")
        ) {
            return false;
        }
        if (securityPermissionDto.getDescription() == null || securityPermissionDto.getDescription().equals("")) {
            return false;
        }
        if (securityPermissionDto.getGroupId() == null || securityPermissionDto.getGroupId().equals("")) {
            return false;
        }
        String permissionId = securityPermissionDto.getPermissionId();
        String description = securityPermissionDto.getDescription();
        String securityGroupId = securityPermissionDto.getGroupId();
        //查询权限组里面是否存在权限
        try {
            SecurityGroupPermission securityGroupPermissions = securityGroupPermissionDao.querySecurityGroupPermission(permissionId, securityGroupId);
            if (securityGroupPermissions == null) {
                //不存在
                SecurityGroupPermission groupPermission = new SecurityGroupPermission();
                groupPermission.setGroupId(securityGroupId);
                groupPermission.setPermissionId(permissionId);
                groupPermission.setCreatedStamp(new Date());
                int i = securityGroupPermissionDao.addSecurityPermissionToSecurityGroup(groupPermission);
                if (i > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override//添加用户登录到权限组（刘浩）
    public int addUserLoginToSecurityGroup(UserLoginSecurityGroup userLoginSecurityGroup) {
        if (userLoginSecurityGroup.getUserLoginId() == null || userLoginSecurityGroup.getUserLoginId().equals("")) {
            return 0;
        }
        if (userLoginSecurityGroup.getGroupId() == null || userLoginSecurityGroup.getGroupId().equals("")) {
            return 0;
        }
        if (userLoginSecurityGroup.getFromDate() == null) {
            userLoginSecurityGroup.setFromDate(new Date());
        }
        userLoginSecurityGroup.setCreatedStamp(new Date());
        //查询用户登录是否在权限组中
        List<UserLoginSecurityGroup> userLoginSecurityGroups = userLoginSecurityGroupDao.queryGroupIdByLoginId(userLoginSecurityGroup.getUserLoginId());
        if (userLoginSecurityGroups.size()!=0) {
            for (UserLoginSecurityGroup loginSecurityGroup : userLoginSecurityGroups) {
                if (loginSecurityGroup.getGroupId() .equals(userLoginSecurityGroup.getGroupId()) ) {
                    return 0;
                }
            }
            //创建权限过期时间
            long l = System.currentTimeMillis();
            long time=l+1000*60*60*24;
            Date thdate = new Date(time);
            userLoginSecurityGroup.setThruDate(thdate);
            return securityGroupDao.addUserLoginToSecurityGroup(userLoginSecurityGroup);
        }
            //创建权限过期时间
            long l = System.currentTimeMillis();
            long time=l+1000*60*60*24;
            Date thdate = new Date(time);
            userLoginSecurityGroup.setThruDate(thdate);
            return securityGroupDao.addUserLoginToSecurityGroup(userLoginSecurityGroup);
    }

    @Override//创建用户登录（刘浩）
    public int createUserLogin(UserLogin userLogin) {
        if (userLogin.getPartyId() == null || userLogin.getUserLoginId() == null || userLogin.getCurrentPassword() == null) {
            return 0;
        }
        if (userLogin.getPartyId().equals("") || userLogin.getUserLoginId().equals("") || userLogin.getCurrentPassword().equals("")) {
            return 0;
        }
        try {
            String newPassword = MD5Util.getMd5Str(userLogin.getCurrentPassword());
            userLogin.setCurrentPassword(newPassword);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        userLogin.setCreatedStamp(new Date());
        UserLogin userLoginResoult = userLoginDao.queryById(userLogin.getUserLoginId());
        if (userLoginResoult!=null){
         return 0;
        }
        return userLoginDao.createUserLogin(userLogin);
    }

    @Override // ===创建新的权限组（刘浩）
    public int createSecurityGroup(String groupId, String description) {
        if (groupId == null || description == null) {
            return 0;
        }
        if (groupId.equals("") || description.equals("")) {
            return 0;
        }
        SecurityGroup securityGroup = new SecurityGroup();
        securityGroup.setGroupId(groupId);
        securityGroup.setDescription(description);
        securityGroup.setCreatedStamp(new Date());
        SecurityGroup securityGroup1 = securityGroupDao.querySecurityGroupById(securityGroup.getGroupId());
        if (securityGroup1!=null){
            return 0;
        }
        return securityGroupDao.createSecurityGroup(securityGroup);

    }

    @Override  //修改权限组 (张鹏程)//
    public int updateSecurityGroup(SecurityGroup securityGroup) {

        if (securityGroup.getGroupId() == null || securityGroup.getGroupId().equals("")) {
            return 0;
        } else if (securityGroup.getDescription() == null || securityGroup.getDescription().equals("")) {
            return 0;
        } else if (securityGroup.getCreatedStamp() == null || securityGroup.getCreatedStamp().equals("")) {
            return 0;
        } else if (securityGroup.getCreatedTxStamp() == null || securityGroup.getCreatedTxStamp().equals("")) {
            return 0;
        } else if (securityGroup.getLastUpdatedStamp() == null || securityGroup.getLastUpdatedStamp().equals("")) {
            return 0;
        } else if (securityGroup.getLastUpdatedTxStamp() == null || securityGroup.getLastUpdatedTxStamp().equals("")) {
            return 0;
        }

        try {
            securityGroup.setLastUpdatedStamp(new Date());
            securityGroup.setLastUpdatedTxStamp(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }


        return securityGroupDao.updateSecurityGroup(securityGroup);
        //return 1;
    }

    @Override //(张鹏程) 创建权限//
    public int createSecurityPermission(SecurityPermission securityPermission) {
        if (securityPermission.getPermissionId() == null || securityPermission.getDescription() == null
                || securityPermission.getCreatedStamp() == null || securityPermission.getCreatedTxStamp() == null
                || securityPermission.getLastUpdatedStamp() == null || securityPermission.getLastUpdatedTxStamp() == null) {
            return 0;
        } else if (securityPermission.getPermissionId().equals("") || securityPermission.getDescription().equals("")
                || securityPermission.getCreatedTxStamp().equals("") || securityPermission.getCreatedStamp().equals("")
                || securityPermission.getLastUpdatedTxStamp().equals("") || securityPermission.getLastUpdatedStamp().equals("")) {
            return 0;
        }

        try {

            //成功//

            securityPermission.setLastUpdatedTxStamp(new Date());
            securityPermission.setLastUpdatedStamp(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return securityPermissionDao.createSecurityPermission(securityPermission);
        //return 1;

    }

    @Override //(张鹏程) 修改权限
    public int updateSecurityPermission(SecurityPermission securityPermission) {


        if (securityPermission.getPermissionId() == null || securityPermission.getPermissionId().equals("")) {
            return 0;
        } else if (securityPermission.getDescription() == null || securityPermission.getDescription().equals("")) {
            return 0;
        } else if (securityPermission.getLastUpdatedStamp() == null || securityPermission.getLastUpdatedStamp().equals("")) {
            return 0;
        } else if (securityPermission.getLastUpdatedTxStamp() == null || securityPermission.getLastUpdatedTxStamp().equals("")) {
            return 0;
        } else if (securityPermission.getCreatedStamp() == null || securityPermission.getCreatedStamp().equals("")) {
            return 0;
        } else if (securityPermission.getCreatedTxStamp() == null || securityPermission.getCreatedTxStamp().equals("")) {
            return 0;
        }

        try {

            securityPermission.setLastUpdatedStamp(new Date());
            securityPermission.setLastUpdatedTxStamp(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return securityPermissionDao.updateSecurityPermission(securityPermission);
        // return 1;
    }

    @Override  //12 (张鹏程) 从权限组中移除权限 //
    public boolean removeSecurityPermissionFromSecurityGroup(String permissionId, String groupId) {
        if (permissionId == null || permissionId.equals("")) {
            return false;
        } else if (groupId == null || groupId.equals("")) {
            return false;
        }


        //return true;
        return securityGroupPermissionDao.removeSecurityPermissionFromSecurityGroup(permissionId, groupId);
    }

    @Override //修改用户登录(白伟)
    public boolean updateUserLoginToSecurityGroup(UserLoginSecurityGroup userLoginSecurityGroup) {
        if (userLoginSecurityGroup.getUserLoginId() == null || userLoginSecurityGroup.getUserLoginId().equals("")) {
            return false;
        }
        if (userLoginSecurityGroup.getFromDate() == null || userLoginSecurityGroup.getFromDate().equals("")) {
            return false;
        }
        if (userLoginSecurityGroup.getGroupId() == null || userLoginSecurityGroup.getGroupId().equals("")) {
            return false;
        }
        if (userLoginSecurityGroup.getThruDate() == null || userLoginSecurityGroup.getThruDate().equals("")) {
            return false;
        }
        try {
            int result = userLoginSecurityGroupDao.updateByUserLoginIdAndGroupIdAndFromDate(userLoginSecurityGroup);
            if (result == 0)
                return false;
            else
                return true;
        } catch (Exception exception) {
            this.logger.error("dao层中userLoginSecurityGroupDao.updateByUserLoginIdAndGroupIdAndFromDate报错");
            return false;
        }
    }

    @Override//从权限组中删除用户登录(白伟)
    public boolean removeUserLoginToSecurityGroup(UserLoginSecurityGroup userLoginSecurityGroup) {
        userLoginSecurityGroup.setThruDate(new Date());
        return this.updateUserLoginToSecurityGroup(userLoginSecurityGroup);
    }

    @Deprecated
    @Override//权限检查(白伟)
    public Set<SecurityPermission> securityPermissionCheck(UserLogin userLogin) {
        Set<SecurityPermission> securityPermissionSet = null;
        List<SecurityPermission> securityPermissionList = userLoginSecurityGroupDao.queryByUserLogin(userLogin);
        if (securityPermissionList == null || securityPermissionList.size() == 0) {
            return securityPermissionSet;
        } else {
            securityPermissionSet = new HashSet<SecurityPermission>(securityPermissionList);
        }
        return securityPermissionSet;
    }

    @Override //创建用户登录的安全提示问题(白伟)
    public boolean createUserLoginSecurityQuestion(UserLoginSecurityQuestion userLoginSecurityQuestion) {
        if (userLoginSecurityQuestion == null) return false;
        String userLoginId = userLoginSecurityQuestion.getUserLoginId();//用户id
        String questionEnumId = userLoginSecurityQuestion.getQuestionEnumId();//问题id
        String answer = userLoginSecurityQuestion.getSecurityAnswer();//问题内容
        if (questionEnumId == null || questionEnumId.equals("")) {
            return false;
        }
        if (userLoginId == null || userLoginId.equals("")) {
            return false;
        }
        if (answer == null || answer.equals("")) {
            return false;
        }
        if (answer.length() > 100) {
            return false;//答案的长度不过超过100个字
        }
        try {
            int flag = userLoginSecurityQuestionDao.insertSecurityQuestion(userLoginSecurityQuestion);
            if (flag > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            this.logger.error("dao层中userLoginSecurityQuestionDao.insertSecurityQuestion报错");
            return false;
        }
    }

    @Override////修改用户登录的安全提示问题（王实）
    public Boolean updateUserLoginSecurityQuestion(UserLoginSecurityQuestion userLoginSecurityQuestion) {
        if (userLoginSecurityQuestion == null) {
            return false;
        }
        String userLoginId = userLoginSecurityQuestion.getUserLoginId();//用户id
        String questionEnumId = userLoginSecurityQuestion.getQuestionEnumId();//问题id
        String answer = userLoginSecurityQuestion.getSecurityAnswer();//问题内容
        userLoginSecurityQuestion.setLastUpdatedStamp(new Timestamp(new Date().getTime()));
        userLoginSecurityQuestion.setLastUpdatedTxStamp(new Timestamp(new Date().getTime()));
        if (questionEnumId == null || questionEnumId.equals("")) {
            return false;
        }
        if (userLoginId == null || userLoginId.equals("")) {
            return false;
        }
        if (answer == null || answer.equals("")) {
            return false;
        }
        //检查是否存在对应的用户和问题
        if (userLoginDao.queryById(userLoginId) != null && userLoginSecurityQuestionDao.queryUserLoginSecurityQuestionById(questionEnumId) != null) {
            try {
                //调用dao层 返回数据
                userLoginSecurityQuestion.setLastUpdatedStamp(new Timestamp(new Date().getTime()));
                userLoginSecurityQuestion.setLastUpdatedTxStamp(new Timestamp(new Date().getTime()));
                int flag = userLoginSecurityQuestionDao.updateSecurityQuestion(userLoginSecurityQuestion);//更新的时候维护时间戳
                if (flag > 0) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    @Override//删除用户登录的安全提示问题（王实）
    public Boolean removeUserLoginSecurityQuestion(UserLoginSecurityQuestion userLoginSecurityQuestion) {
        if (userLoginSecurityQuestion == null) {
            return false;
        }
        String userLoginId = userLoginSecurityQuestion.getUserLoginId();//用户id
        String questionEnumId = userLoginSecurityQuestion.getQuestionEnumId();//问题id
        if (questionEnumId == null || questionEnumId.equals("")) {
            return false;
        }
        if (userLoginId == null || userLoginId.equals("")) {
            return false;
        }
        //检查是否存在对应的用户和问题
        if (userLoginDao.queryById(userLoginId) != null && userLoginSecurityQuestionDao.queryUserLoginSecurityQuestionById(questionEnumId) != null) {
            try {
                //调用dao层 返回数据
                int flag = userLoginSecurityQuestionDao.deleteSecurityQuestion(userLoginSecurityQuestion);
                if (flag > 0) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override//删除权限组（王实）
    public Boolean deleteSecurityGroup(String groupId) {
        if (groupId == null || groupId.equals("")) {
            return false;
        }
        List<SecurityGroupPermission> securityGroupPermissions = securityGroupPermissionDao.querySecurityGroupPermission(groupId);
        if (securityGroupPermissions.size() > 0) {
            List<String> list = new ArrayList<>();
            for (SecurityGroupPermission securityGroupPermission : securityGroupPermissions) {
                String permissionId = securityGroupPermission.getPermissionId();
                list.add(permissionId);
            }
            if (securityGroupPermissionDao.deleteSecurityGroupPermission(list, groupId) > 0) {//删除中间表的引用（securityGroupPermission）
                //删除权限组
                if (securityGroupDao.deleteSecurityGroup(groupId) > 0) {
                    return true;
                }
            }
            /*//删除权限组中的权限
            securityPermissionDao.deletePermissionList(list);//有问题，不应删除权限*/
        }
        return false;

    }

    public UserLoginSecurityQuestionDao getUserLoginSecurityQuestionDao() {
        return userLoginSecurityQuestionDao;
    }

    public void setUserLoginSecurityQuestionDao(UserLoginSecurityQuestionDao userLoginSecurityQuestionDao) {
        this.userLoginSecurityQuestionDao = userLoginSecurityQuestionDao;
    }

    public SecurityPermissionDao getSecurityPermissionDao() {
        return securityPermissionDao;
    }

    public void setSecurityPermissionDao(SecurityPermissionDao securityPermissionDao) {
        this.securityPermissionDao = securityPermissionDao;
    }

    public UserLoginSecurityGroupDao getUserLoginSecurityGroupDao() {
        return userLoginSecurityGroupDao;
    }

    public void setUserLoginSecurityGroupDao(UserLoginSecurityGroupDao userLoginSecurityGroupDao) {
        this.userLoginSecurityGroupDao = userLoginSecurityGroupDao;
    }

    public SecurityGroupPermissionDao getSecurityGroupPermissionDao() {
        return securityGroupPermissionDao;
    }

    void setSecurityGroupPermissionDao(SecurityGroupPermissionDao securityGroupPermissionDao) {
        this.securityGroupPermissionDao = securityGroupPermissionDao;
    }

    public UserLoginDao getUserLoginDao() {
        return userLoginDao;
    }

    public void setUserLoginDao(UserLoginDao userLoginDao) {
        this.userLoginDao = userLoginDao;
    }

    public SecurityGroupDao getSecurityGroupDao() {
        return securityGroupDao;
    }

    public void setSecurityGroupDao(SecurityGroupDao securityGroupDao) {
        this.securityGroupDao = securityGroupDao;
    }

    //修改用户登录 (白伟)
    public Boolean updateUserLogin(UserLogin userLogin) {
        if (userLogin == null) return false;
        if (userLogin.getUserLoginId() == null || userLogin.getUserLoginId().equals("")) {
            return false;
        }
        try {
            int i = userLoginDao.updateByUserLoginId(userLogin);
            if (i > 0)
                return true;
            else
                return false;
        } catch (Exception e) {
            this.logger.error("dao层中userLoginDao.updateByUserLoginId报错");
            return false;
        }
    }

    //修改用户的密码(白伟)
    public Boolean updateUserLoginPassword(String userLoginId, String currentPassword, String newpassword) {
        if (userLoginId == null || userLoginId.equals("")) {
            return false;
        }
        if (currentPassword == null || currentPassword.equals("")) {
            return false;
        }
        if (newpassword == null || newpassword.equals("")) {
            return false;
        }
        try {
            UserLogin userLogin = userLoginDao.queryByUserLogin(new UserLogin(userLoginId, currentPassword));
            if (userLogin == null) {
                return false;//当前的用户名或者密码不对,不允许修改密码
            }
        } catch (Exception e) {
            this.logger.error("dao层中userLoginDao.queryByUserLogin报错");
            return false;
        }
        try {
            int i = userLoginDao.updateByUserLoginIdAndCurrentPassword(userLoginId, newpassword);
            if (i > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            this.logger.error("dao层中userLoginDao.updateByUserLoginIdAndCurrentPassword报错");
            return false;
        }
    }
}
